<link rel="stylesheet" type="text/css" href="/assets/third-party/datatables/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="/assets/css/dataTables.bootstrap.css">
<link rel="stylesheet" type="text/css" href="/assets/third-party/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css">
<link rel="stylesheet" type="text/css" href="/assets/third-party/select2-3.5.1/select2.css">

<style type="text/css">
	.il{
		display: inline;
	}
	.form-group .control-label{
		padding-right: 5px;
	}
	.form-group .col-sm-7{
		padding-left: 5px;
	}
	.form-group input, .form-group select{
		width: 92%;
		display: inline;
	}
	#dataLoading{
		 width: 100%;
		 margin:  0px  0px 10px 0px;
		 text-align: center;
	}
	#tableLearn td{
		font-size: 10px;
	}
</style>

<div class="container" style="margin-top: 60px;">
	<div class="row">
		<div class="col-lg-12">
			<form method="GET">
				<select name="student_id" class="form-control il" style="width: 150px;">
					<option value="">全部学生</option>
					<?php if($students){ ?>
					    <?php foreach ($students as $key => $value) { ?>
					    <option value="<?php echo $value->id; ?>"<?php echo $value->id == \Input::get('student_id', false) ? ' selected="selected"' : ''?>><?php echo $value->people->first_name . $value->people->last_name; ?></option>
					    <?php } ?>
					<?php } ?>
				</select>
				<select id='search_course_id' name="course_id" class="form-control il" style="width: 150px; height: 34px;">
					<option value="">全部课程</option>
				</select>
				<select name="teacher_id" class="form-control il" style="width: 150px;">
					<option value="">全部教师</option>
					<?php if($teachers){ ?>
					    <?php foreach ($teachers as $key => $value) { ?>
					    <option value="<?php echo $value->id; ?>"<?php echo $value->id == \Input::get('teacher_id', false) ? ' selected="selected"' : ''?>><?php echo $value->people->first_name . $value->people->last_name; ?></option>
					    <?php } ?>
					<?php } ?>
				</select>
				<button type="submit" class="btn btn-info"> <i class="fa fa-search"></i> 查询 </button>
				<a class="btn btn-success" data-toggle="modal" data-target="#learnRecordModal"> <i class="fa fa-plus"></i> 新增学习记录 </a>
				<a class="btn btn-primary" data-toggle="modal" data-target="#modal-upload"> <i class="fa fa-file-excel-o"></i> 文件导入 </a>
				<a href="/uploads/files/format.xlt">下载Excel格式文件</a>
				<!--<a href="#" class="btn btn-success"> <i class="fa fa-plus"></i> 全选 </a>
				<a href="#" class="btn btn-danger"> <i class="fa fa-plus"></i> 批量删除 </a>
				<a href="#" class="btn btn-danger"> <i class="fa fa-plus"></i> 刷新 </a>-->
			</form>
		</div>
	</div>
	<div class="row" style="margin-top: 10px;">
		<div class="col-lg-12">
			<div class="panel panel-default">
                <div class="panel-heading">
                    学习记录列表
                </div>
                <!-- /.panel-heading -->
                <div class="panel-body">
					<table class="table table-bordered table-hover" role="datatables">
						<thead>
							<tr>
								<th>ID</th>
								<th>学生</th>
								<th>课程</th>
								<th>上课时间</th>
								<th>表现</th>
								<th>教师</th>								
								<th>创建时间</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody id="learnRecords">
							<?php foreach ($items as $key => $value) { ?>
							<tr data-id="<?php echo $value->id; ?>">
								<td><?php echo $value->id; ?></td>
								<td><?php echo "{$value->student->people->first_name}{$value->student->people->last_name}"; ?></td>
								<td><?php echo $value->course->name; ?></td>
								<td><?php echo date('Y-m-d H:i:s', $value->learn_start) . '至' . date('Y-m-d H:i:s', $value->learn_end); ?></td>
								<td><?php echo $value->remark; ?></td>
								<td><?php echo "{$value->teacher->people->first_name}{$value->teacher->people->last_name}"; ?></td>
								<td><?php echo date('Y-m-d H:i:s', $value->created_at); ?></td>
								<td>
									<a href="#" role="edit" class="btn btn-sm btn-info" data-toggle="modal" data-target="#learnRecordModal"> <i class="fa fa-pencil-square-o"></i> 编辑 </a>
									<a href="#" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#confirmModal"> <i class="fa fa-trash-o"></i> 删除 </a>
								</td>
							</tr>
							<?php } ?>							
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
</div>

<!-- 学习记录详情模态框 -->
<div class="modal fade" id="learnRecordModal" tabindex="-1" role="dialog" aria-labelledby="learnRecordModalTitle" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
				<h4 class="modal-title" id="learnRecordModalTitle"> 学习记录资料 </h4>
			</div>
			<div class="modal-body">
				<form id="frmRecord" class="form" role="form" action="/admin/student/learn_create" method="post">
					<div class="form-group">
						<label for="student_id">学生</label>
						<select id="student_id" name="student_id" class="form-control">
							<?php  if($students){ ?>
							    <?php foreach ($students as $key => $value) { ?>
							    <option value="<?php echo $value->id; ?>"<?php echo $value->id == \Input::get('student_id', false) ? ' selected="selected"' : ''; ?>><?php echo $value->people->first_name . $value->people->last_name; ?></option>
							    <?php } ?>
							<?php } ?>
						</select>
					</div>
					<div class="form-group">
						<label for="course_id">课程</label>
						<select id="course_id" name="course_id" style="width: 92%;"></select>
					</div>
					<div class="form-group">
						<label for="teacher_id">教师</label>
						<select id="teacher_id" name="teacher_id" class="form-control">
							<?php  if($teachers){ ?>
							    <?php foreach ($teachers as $key => $value) { ?>
							    <option value="<?php echo $value->id; ?>"><?php echo $value->people->first_name . $value->people->last_name; ?></option>
							    <?php } ?>
							<?php } ?>
						</select>
					</div>
					<div class="form-group">
						<label for="learn_start">时间</label>
						<input type="text" class="form-control" id="learn_start" name="learn_start" placeholder="上课时间" style="width: 46%; display: inline;" role="datetime">
						<input type="text" class="form-control" id="learn_end" name="learn_end" placeholder="下课时间" style="width: 46%; display: inline;" role="datetime">
					</div>
					<div class="form-group">
						<label for="remark">表现</label>
						<textarea class="form-control" id="remark" name="remark" placeholder="上课表现" style="width: 100%; display: inline;"></textarea>
					</div>
				</form>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal"> 取消 </button>
				<button type="button" id="btnSave" class="btn btn-primary"> 保存 </button>
			</div>
		</div>
	</div>
</div>

<!-- 导入文件模态框 -->
<div class="modal fade" id="importModal" tabindex="-1" role="dialog" aria-labelledby="importModalTitle" aria-hidden="true">
	<div class="modal-dialog modal-lg" style="margin-bottom: 0px;">
		<div class="modal-content">
			<div class="modal-header">
		        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
		        <h4 class="modal-title" id="importModalTitle">通过Excel导入学习记录</h4>
		     </div>
			<div class="modal-body" style="overflow-y:scroll;">
				<table class="table table-bordered" id="tableLearn">
					<thead>
						<tr>
							<th style="width: 60px;">学生</th>
							<th>课程</th>
							<th style="width: 90px;">上课时间</th>
							<th>表现</th>
							<th style="width: 60px;">教师</th>
							<th>数据状态</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody id="learns">
					</tbody>
				</table>
			</div>
			<div class="modal-footer">
				<div class="row">
					<div class="col-xs-4" style="text-align: left;">
						共 <span id="totalRecords">0</span> 条，
						<font color="#f00;">错误 <span id="errorRecords">0</span> 条</font>
					</div>
					<div class="col-xs-4">
					</div>
					<div class="col-xs-4">
						<button type="button" class="btn btn-default" data-dismiss="modal"> 取消 </button>
						<button type="button" id="btnSubmitImport" class="btn btn-success"> 确认导入 </button>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<!-- 确认删除模态框 -->
<div class="modal fade" id="confirmModal" tabindex="-1" role="dialog" aria-labelledby="confirmModalTitle" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-body">
				<div class="alert alert-warning">
					<strong>确定删除？</strong>
					<p>删除该学习记录，学生及家长将无法查看该记录!</p>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal"> 取消 </button>
				<button type="button" id="btnConfirm" class="btn btn-danger"> 确认删除 </button>
			</div>
		</div>
	</div>
</div>

<?php echo render('edu/public/upload'); ?>
<script type="text/javascript">
    var path = 'files';
    var imgpanel = '';
    var filePath = '';

    function callback(file, data){
        var json = eval('(' + data + ')');
        if(json.status == 'succ'){
        	filePath = json.data;
        	$('#modal-upload').modal('hide');
        	readData();
        }else{
            alert(json.msg);
        }
    }

    function readData(){
    	$('#importModal').modal('show');
    	$('#learns').empty();
    	$('#learns').append('<tr>'
			 + '<td colspan="7" style="text-align:center;">'
			 + '<i class="fa fa-spinner fa-spin"></i> 数据解析中,请稍等...'
			 + '</td>'
			 + '</tr>');

    	setTimeout(function(){
    		$.post('/admin/student/learn_import', 
    		{
    			file: filePath
    		}, 
    		function(data, status){
    			if(data.status == 'err'){    				
    				return;
    			}

    			var errors = 0;
    			$('#learns').empty();
    			var items = data.data;
    			for (var i = 0; i < items.length; i++) {
    				if(items[i].student_id < 1 || items[i].teacher_id < 1 || items[i].course_id < 1){
    					errors ++;
    				}
    				$('#learns').append(course_tr, items[i], null);
    			}
    			$('#totalRecords').text(items.length);
    			$('#errorRecords').text(errors);
    			
    		}, 'json');
    	}, 1500);
    	
    }
</script>

<script type="text/javascript" src="/assets/third-party/jquery-tmpl-master/jquery.tmpl.min.js"></script>
<script type="text/javascript" src="/assets/third-party/jquery-tmpl-master/jquery.tmplPlus.min.js"></script>
<script type="text/x-jquery-tmpl" id="tr">
<tr>
	<td>${id}</td>
	<td><span class="hide">${name}</span><input type="text" value="${name}" placeholder="级别名称"  style="width: 70px;"/></td>
	<td><span class="hide">${sort}</span><input type="text" value="${sort}" placeholder="排序" style="width: 30px;" /></td>
	<td>
		<a role="save" class="btn btn-sm btn-success"> <i class="fa fa-check"></i> 保存 </a>
		<a role="edit" class="btn btn-sm btn-info hide"> <i class="fa fa-pencil-square-o"></i> 编辑 </a>
		<a role="del" class="btn btn-sm btn-danger hide"> <i class="fa fa-trash-o"></i> 删除 </a>
	</td>
</tr>
</script>
<script type="text/x-jquery-tmpl" id="course_tr">
<tr index='${index}' student_id='${student_id}' course_id='${course_id}' teacher_id='${teacher_id}' learn_start='${learn_start_date}' learn_end='${learn_end_date}' data-value='${remark}'>
	<td>${student_name}</td>
	<td>${course_name}</td>
	<td>${learn_start_date}</td>
	<td><a class="btn btn-xs btn-default" title="${remark}"> <i class="fa fa-search"></i> 悬停查看</a></td>
	<td>${teacher_name}</td>
	<td>
		{{if student_id == 0}}
		<label class="label label-danger">学生不存在</label>
		{{else student_id == -1}}
			<select name="student_id">
				<option value="0">学生重名，请选择</option>
				{{each(i, item) students}}
				<option value="${item.id}">${item.name}</option>
				{{/each}}
			</select>
		{{/if}}
		{{if teacher_id == 0}}
		<label class="label label-danger">教师不存在</label>
		{{else teacher_id == -1}}
			<select name="teacher_id">
				<option value="0">教师重名，请选择</option>
				{{each(i, item) teachers}}
				<option value="${item.id}">${item.name}</option>
				{{/each}}
			</select>
		{{/if}}
		{{if course_id == 0}}
		<label class="label label-danger">课程不存在</label>
		{{else course_id == -1}}
			<select name="course_id">
				<option value="0">课程重名，请选择</option>
				{{each(i, item) courses}}
				<option value="${item.id}">${item.name}</option>
				{{/each}}
			</select>
		{{/if}}
		{{if student_id > 0 && teacher_id > 0 && course_id > 0}}
			<label class="label label-default">就绪</label>
		{{/if}}
	</td>
	<td>
		{{if student_id < 1 || teacher_id < 1 || course_id < 1}}
			<a href='#' class="btn btn-sm btn-danger">删除</a>
		{{/if}}
	</td>
</tr>
</script>

<script type="text/javascript" src="/assets/third-party/datatables/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="/assets/js/dataTables.bootstrap.js"></script>

<script type="text/javascript" src="/assets/third-party/select2-3.5.1/select2.min.js"></script>
<script type="text/javascript">
	var flag = false;
	var count = 0;

	$(function(){

		$('table[role="datatables"]').dataTable({
	        "oLanguage": {
	            "sLengthMenu": "每页显示 _MENU_ 条记录",
	            "sZeroRecords": "很抱歉，未找到相关数据",
	            "sInfo": "从 _START_ 至 _END_ /共 _TOTAL_ 条数据",
	            "sInfoEmpty": "没有符合条件的数据",
	            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
	            "sSearch": "搜索：",
	            "oPaginate": {  
					"sFirst": "首页",  
					"sPrevious": "上一页",
					"sNext": "下一页",
					"sLast": "末页"
				}  
	        },
	        fnDrawCallback: function(){

	            if(window.flag == false){
	        		window.flag = true;
	        		var index = localStorage.getItem('pagination_index');
	                localStorage.removeItem('pagination_index');
		        	if( ! index){
		        		index = 1;
		        	}
		        	index -= 1;

		        	$('table[role="datatables"]').dataTable().fnPageChange(index);
	                
	        	}
            }
	    });

	    $('#learns').delegate('select', 'change', function(){
	    	$(this).parents('tr').attr($(this).attr('name'), $(this).val())

	    	var select = $(this).parent().find('select');
	    	var succ = true;
	    	for (var i = 0; i < select.length; i++) {
	    		if(parseInt($(select[i]).val()) < 1){
	    			succ = false;
	    			break;
	    		}
	    	}

	    	if(succ){
	    		$('#errorRecords').text(parseInt($('#errorRecords').text()));
	    		$(this).parent().html('<label class="label label-default">就绪</label>');
	    	}
	    });

		$('#importModal').find('.modal-body').css('max-height', (window.screen.availHeight - 60 - 56 - 65 - 60) + 'px');

		$('table[role="datatables"]').delegate('a[data-target="#confirmModal"]', 'click', function(){
	    	$('#btnConfirm').attr('data-id', $(this).parent().parent().attr('data-id'));
	    });

	    $('#btnConfirm').click(function(){
	    	var id = $(this).attr('data-id');
	    	$.get('/admin/student/learn_delete/' + id,
	    		function(data, status){
	    			if(data.status == 'succ'){
	    				$('#learnRecords').find('tr[data-id="' + id + '"]').remove();
	    				$('#confirmModal').modal('hide');
	    			}
	    		}, 'json');
	    });

	    $('#btnSubmitImport').click(function(){
	    	if(parseInt($('#errorRecords').text()) > 0){
	    		alert('请将所有错误处理完再试');
	    		return;
	    	}

	    	if($(this).text() == '导入完毕'){
	    		window.location.reload();
	    		$('#importModal').modal('hide');
	    		return;
	    	}

	    	$(this).text('导入中...');
	    	$(this).addClass('disabled');

	    	var tr = $('#learns').find('tr');
	    	for (var i = 0; i < tr.length; i++) {
	    		var status = $(tr[i]).find('td').eq(5).text().trim();
	    		if(status != '就绪'){
	    			continue;
	    		}

	    		var post_data = {
	    			index: $(tr[i]).attr('index'),
	    			learn_start: $(tr[i]).attr('learn_start'),
	    			learn_end: $(tr[i]).attr('learn_end'),
	    			student_id: $(tr[i]).attr('student_id'),
					course_id: $(tr[i]).attr('course_id'),
					teacher_id: $(tr[i]).attr('teacher_id'),
					remark: $(tr[i]).attr('data-value'),
	    		}

	    		$(tr[i]).find('td').eq(5).html('<label class="label label-warning"><i class="fa fa-spinner fa-spin"></i> 导入中...</label>');
	    		$.post('/admin/student/learn_create', 
	    			post_data,
	    			function(data, status){
	    				count ++;
	    				if(count >= $('#learns').find('tr').length){
	    					$('#btnSubmitImport').text('导入完毕');
	    					$('#btnSubmitImport').removeClass('disabled');
	    				}
	    				if(data.status == 'err'){
	    					$('#learns').find('tr[index=' + data.data + ']').find('td:eq(5)').text('<label class="label label-danger"><i class="fa fa-close"></i> 导入失败</label>');
	    					return;
	    				}
	    				$('#learns').find('tr[index=' + data.data + ']').find('td:eq(5)').html('<label class="label label-success"><i class="fa fa-check"></i> 导入成功</label>');
	    			}, 'json');
	    	}
	    	
	    });

	    $('table[role="datatables"]').delegate('a[data-target="#learnRecordModal"]', 'click', function(){

	    	/*$('#student_id').val('');
	    	$('#course_id').val('');
	    	$('#teacher_id').val('');*/
	    	$('#learn_start').val('');
	    	$('#learn_end').val('');
	    	$('#remark').val("");

	    	if($(this).attr('role') == 'edit'){
	    		localStorage.setItem('pagination_index', $('.pagination .active').find('a').text());
	    		$('#frmRecord').attr('action', '/admin/student/learn_edit/' + $(this).parent().parent().attr('data-id'));
	    		$.get('/admin/student/learn_view/' + $(this).parent().parent().attr('data-id'), 
	    			function(data, status){
	    				if(data.status == 'succ'){
	    					var item = data.data;
	    					$('#student_id').val(item.student_id);
	    					$('#course_id').select2('val', item.course_id);
	    					$('#learn_start').val(item.learn_start);
	    					$('#learn_end').val(item.learn_end);
	    					$('#teacher_id').select2('val', item.teacher_id);
	    					$('#remark').val(item.remark);
	    				}
	    			}, 'json');
	    	}else{
	    		$('#frmRecord').attr('action', '/admin/student/learn_create/');
	    	}
	    });

		$("#course_id").select2({placeholder: "请选择教授课程"});

		$.get('/admin/course', 
			function(data, status){
				if(data.status == 'succ'){
					var courses = data.data;
					var grades = data.grades;
					for (var i = 0; i < grades.length; i++) {
						var str = '';
						for (var j = 0; j < courses.length; j++) {
							if(courses[j].grade_id == grades[i].id){
								str += "<option value='" + courses[j].id + "'>" + courses[j].name + "</option>";
							}
						}
						$('#search_course_id').append("<optgroup label='" + grades[i].name + "'>" + str + "</optgroup>");
						$('#course_id').append("<optgroup label='" + grades[i].name + "'>" + str + "</optgroup>");
					}
				}

			}, 'json');
	});
</script>

<script type="text/javascript" src="/assets/third-party/parsley/parsley.min.js"></script>
<script type="text/javascript" src="/assets/third-party/parsley/i18n/zh_cn.js"></script>
<script type="text/javascript" src="/assets/third-party/parsley/i18n/zh_cn.extra.js"></script>
<script type="text/javascript">
	$(function(){
		$('#btnSave').click(function(){
			$('#frmRecord').submit();
		});
	});
</script>

<script type="text/javascript" src="/assets/third-party/bootstrap-datetimepicker-master/js/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript" src="/assets/third-party/bootstrap-datetimepicker-master/js/locales/bootstrap-datetimepicker.zh-CN.js" charset="UTF-8"></script>
<script type="text/javascript">
$(function(){
	$('input[role="datetime"]').datetimepicker({
		language: 'zh-CN'
	});
});
</script>